package com.vision.bigDataApi.interceptor;

import com.vision.bigDataApi.enums.ReturnStatus;
import com.vision.bigDataApi.model.InterfaceInfo;
import com.vision.bigDataApi.service.common.ResultService;
import com.vision.bigDataApi.service.mysql.UserService;
import com.vision.bigDataApi.utils.ClientUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.*;

@Component
public class MyInterceptor implements HandlerInterceptor {
    private Date reqTime;
    private Date respTime;

    @Autowired
    private ResultService resultService;
    @Autowired
    private UserService userService;


    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
            throws Exception {
        boolean url = ClientUtils.isUrl(request.getRequestURL().toString());
        if(!url){
            response.getWriter().print(resultService.result(ReturnStatus.FAILURE,null,"地址无效",null));
        }
        reqTime = new Date(System.currentTimeMillis());
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest req, HttpServletResponse resp, Object handler,
                           ModelAndView modelAndView) throws Exception {
        respTime=new Date(System.currentTimeMillis());
        String reqURI = req.getRequestURI();
        String[] str = reqURI.split("/");
        //将客户端ip等信息写入接口日志表中
        if(str.length>1){
           if("gkgl".equals(str[1])||"slyz".equals(str[1])){
               List<InterfaceInfo> listMap = userService.getByInterfaceInfo(reqURI);
               Map<String,Object> map=new HashMap<String,Object>();
               map.put("iName",reqURI);
               map.put("lClientIp", ClientUtils.getIpAddress(req));
               map.put("lReqTime",new java.sql.Timestamp(reqTime.getTime()));
               map.put("lRespTime",new java.sql.Timestamp(respTime.getTime()));
               map.put("iId",listMap.get(0).getIId());
                userService.insertLogInterface(map);
           }
        }

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
            throws Exception {

    }
}